<?php

namespace app\api\logic;

use app\common\enum\EsSearchKeyEnum;
use app\common\exception\BusinessException;
use app\common\model\AppConfig;
use app\common\model\CourseQuestion;
use app\common\model\CourseQuestionCategory;
use app\common\model\UserCourse;
use app\common\model\AnswerQuestion;
use app\common\model\CourseLearnStats;
use app\common\model\ExamTime;
use think\db\exception\DbException;

class Course
{

    /**
     * getInfo
     * @param array $param
     * @return void
     * @throws BusinessException
     */
    public function getInfo(array $param = [])
    {
        // 提取参数
        $id = $param['id'];

        // 检查是否虚拟支付
        if (isIosVirtualPay()) {
            throw new BusinessException(config('mcp.ios_not_support_notice'));
        }

        // 查询课程资料
        $field = 'id,code,name';
        $courseInfo = app(\app\common\model\Course::class)->field($field)->find($id);
        if (!$courseInfo) {
            throw new BusinessException('获取课程信息失败');
        }

        // 返回
        return $courseInfo;
    }

    /**
     * 我的课程
     * @param $param
     * @return mixed
     */
    public function myCourse($param): array
    {
        // 提取参数
        $userId = $param['userId'];

        // 查询条件
        $where = [
            ['a.uid', '=', $userId]
        ];

        // 查询数据
        $field = 'course_id,b.code,b.name,a.expire';
        $list = app(UserCourse::class)
            ->alias('a')
            ->field($field)
            ->leftJoin('course b', 'a.course_id = b.id')
            ->where($where)
            ->select();

        // 填充数据
        foreach ($list as $key => $val) {
            $list[$key]['expire_name'] = date('Y-m-d', $val['expire']);
        }

        // 返回
        $list = $list ? $list->toArray() : [];
        return $list;
    }

    /**
     * 我的课程
     * @param $param
     * @return mixed
     */
    public function saleInfo($param): array
    {
        // 提取参数
        $id = $param['id'];
        $appId = getAppId();

        // 查询数据
        $field = 'id,code,name,price,expire,expire_type';
        $courseInfo = app(\app\common\model\Course::class)->field($field)->find($id);
        
        // 添加expire_type_name字段
        if ($courseInfo) {
            $courseModel = app(\app\common\model\Course::class);
            $courseInfo['expire_type_name'] = $courseModel->getExpireTypeName($courseInfo['expire_type']);
        }

        // 查询配置
        $appConfig = app(AppConfig::class);
        $config = $appConfig->getByIdAndType($appId, 'buy_course');

        // 返回
        return [
            'courseInfo' => $courseInfo,
            'noticeList' => $config['buy_notice_list']
        ];
    }

    /**
     * 搜索课程
     * @param $param
     * @return array
     */
    public function search($param): array
    {
        // 提取参数
        $page = $param['page'];
        $size = $param['size'] ?? 10;
        $keyword = trim($param['keyword']);

        // 组装配置的搜索方式
        $searchCourseWay = app(AppConfig::class)->getValueByIdAndTypeWithName(getAppId(), 'search_page_set', 'search_course_way');

        // 根据配置进行数据查询
        $list = $searchCourseWay == 1 ? $this->searchFromDb($page, $size, $keyword) : $this->searchFromEs($page, $size, $keyword);

        // 填充数据
        $newList = [];
        foreach ($list as $key => $val) {
            $allNameValue = [$val['name'], $val['code']];
            $allNameValue = array_filter($allNameValue);
            $newList[] = [
                'id' => $val['id'],
                'name' => join('|', $allNameValue)
            ];
        }

        // 返回
        return $newList;
    }

    /**
     * 获取用户课程学习统计数据
     * @param array $param
     * @return array
     */
    public function getUserStats(array $param): array
    {
        // 提取参数
        $userId = $param['userId'];
        $courseId = $param['course_id'];
        $professionCourseId = $param['profession_course_id'] ?? 0;

        // 获取答题统计数据
        $answerStats = app(AnswerQuestion::class)->getUserAnswerStatsByUidAndCourseId($userId, $courseId);
        
        // 获取课程学习统计数据
        $courseLearnStats = app(CourseLearnStats::class)->getUserCourseStats($userId, $courseId);
        
        // 获取题库考试时间,计算还差多少天考试
        $exam_countdown = app(\app\common\model\ProfessionCourse::class)->getExamCountdown($professionCourseId);

        // 整合数据
        $result = [
            // 今日答题数
            'today_question_count' => $answerStats['today_question_count'],
            // 累计答题数
            'total_question_count' => $answerStats['total_question_count'],
            // 正确率
            'correct_rate' => $answerStats['correct_rate'],
            // 考试倒计时
            'exam_countdown' => $exam_countdown,
        ];

        return $result;
    }

    private function searchFromEs($page, $size, $keyword)
    {
        $from = ($page - 1) * $size;
        $params = [
            'index' => getEsIndex(EsSearchKeyEnum::COURSE_KEY),
            'body' => [
                'query' => [
                    'match' => [
                        'content' => $keyword
                    ],
                ],
                'from' => $from,
                'size' => $size
            ]
        ];
        $client = getEsClient();
        $results = $client->search($params);
        $results->asArray();
        $queryList = $results['hits']['hits'];

        // 提取课程编号
        $allCourseId = array_column($queryList, '_id');
        if (!$allCourseId) {
            return [];
        }

        // 查询数据
        $order = buildSqlOrderByField('id', $allCourseId);
        $where = [['id', 'in', $allCourseId]];
        $list = app(\app\common\model\Course::class)->where($where)->orderRaw($order)->select();
        return $list;
    }

    /**
     * searchFromDb
     * @param $page
     * @param $size
     * @param $keyword
     * @return \app\common\model\Course[]|array|\think\Collection
     * @throws DbException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     */
    private function searchFromDb($page, $size, $keyword)
    {
        $like = '%' . $keyword . '%';
        $list = app(\app\common\model\Course::class)->where('name', 'like', $like)->whereOr('code', 'like', $like)->page($page)->limit($size)->select();
        return $list;
    }

    /**
     * 是否可购买
     * @throws DbException
     */
    public function checkCanBuy($courseId): bool
    {
        //(高级+章节+真题)
        $where = [['course_id', '=', $courseId], ['level', '=', 1], ['tag_id', 'in', [20, 30, 40]]];
        $question_count = app(CourseQuestionCategory::class)->where($where)->sum('question_count');
        if ($question_count) {
            return true;
        }
        return false;
    }
}